<template>
  <div v-loading="loading">
    <el-row type="flex" justify="space-between">
      <el-col :span="6">
        <el-row type="flex" justify="space-between">
          <el-col :span="6">
            <div class="current">
              <span v-if="isNow" class="gl_fs_14">本周</span>
              <span v-else class="gl_fs_14">非本周</span>
            </div>
          </el-col>
          <el-col :span="16" align="right"><div class="class_name gl_ellipsis">{{ className }}</div></el-col>
        </el-row>
      </el-col>
      <el-col :span="12">
        <div class="date">
          <el-button size="mini" class="left_right_btn" type="text" icon="el-icon-arrow-left" @click="toPrev()" />
          <span class="gl_dis_ib gl_middle">{{ firstDay }} ~ {{ lastDay }}</span>
          <el-button size="mini" class="left_right_btn" type="text" @click="toNext()">
            <i class="el-icon-arrow-right el-icon--right" />
          </el-button>
        </div>
      </el-col>
      <el-col :span="6" class="gl_fs_14" align="right">
        <span class="type" :class="[ typeTimeTable == 'day' ? 'type_active': '' ]" @click="changeType('day')">日</span>
        <span class="type" :class="[ typeTimeTable == 'week' ? 'type_active': '' ]" @click="changeType('week')">周</span>
        <span class="type" :class="[ typeTimeTable == 'month' ? 'type_active': '' ]" @click="changeType('month')">月</span>
      </el-col>
    </el-row>
    <div class="gl_mt_5 timetable_week">
      <el-table
        :data="classList"
        :header-cell-class-name="headerCellClassName"
        :cell-class-name="tableCellClassName"
      >
        <el-table-column prop="course" width="60" />
        <el-table-column v-for="(item, index) in propList" :key="index" :prop="item" :render-header="renderHeader">
          <template slot-scope="{ row }">
            <div v-if="row[item] && row[item].length > 3">
              <div
                v-for="(jtem, jndex) in row[item]"
                :key="jndex"
                class="gl_dis_ib class_td"
                :style="{ width: '24px', background: jtem.courseScheduleColor }"
              >
                <Hover :is-order-page="isOrderPage" :class-name="jtem.className" :data="jtem" :week="String(index + 1)" @remove="remove" @edit="edit">
                  <div slot="content" style="height: 80px" @click="toClassTimetable(jtem)">
                    <span>{{ classId ? formatClass(jtem.courseName) : formatClass(jtem.className) }}</span>
                  </div>
                </Hover>
              </div>
            </div>
            <div v-else>
              <div
                v-for="(jtem, jndex) in row[item]"
                :key="jndex"
                class="gl_dis_ib class_td"
                :style="{ width: 100 / row[item].length + '%', background: jtem.courseScheduleColor }"
              >
                <Hover
                  :is-order-page="isOrderPage"
                  :class-name="jtem.className"
                  :data="jtem"
                  :week="String(index + 1)"
                  :code="'get'"
                  @remove="remove"
                  @edit="edit"
                >
                  <div slot="content" @click="toClassTimetable(jtem)">
                    <span>{{ classId ? jtem.courseName : jtem.className }}</span>
                  </div>
                </Hover>
              </div>
            </div>
          </template>
        </el-table-column>
      </el-table>
      <CreateDialog ref="createDialog" @refresh="refresh" />
    </div>
  </div>
</template>

<script>
import Hover from '../hover.vue';
import CreateDialog from '@/components/Class/createDialog.vue';
import { FormatDate } from '@/lib';
import {
  api_GET_ClubCourseSchedule, // 获取课表
  api_GET_ClubCourseScheduleCanBeReservedCourseSchedules, // 预约
  api_DELETE_ClubCourseScheduleId // 删除课表
} from '@/extend/api/hallswaggerApi/app.js';
import {
  Api_GET_ClubCourseScheduleQO
} from '@/lib/form/hall/swaggerForm.js';
export default {
  components: {
    Hover,
    CreateDialog
  },
  props: {
    typeTimeTable: {
      type: String,
      default: 'week'
    },
    searchForm: {
      type: Object,
      default() {
        return {};
      }
    }
  },
  data() {
    return {
      loading: false,
      isOrderPage: false, // 是否是预约管理页面
      className: '',
      classId: '',
      form: new Api_GET_ClubCourseScheduleQO(),
      week: ['one', 'two', 'three', 'four', 'five', 'six', 'seven'],
      dateList: [],
      propList: [],
      initClassList: [
        {
          course: '5:00'
        },
        {
          course: '6:00'
        },
        {
          course: '7:00'
        },
        {
          course: '8:00'
        },
        {
          course: '9:00'
        },
        {
          course: '10:00'
        },
        {
          course: '11:00'
        },
        {
          course: '12:00'
        },
        {
          course: '13:00'
        },
        {
          course: '14:00'
        },
        {
          course: '15:00'
        },
        {
          course: '16:00'
        },
        {
          course: '17:00'
        },
        {
          course: '18:00'
        },
        {
          course: '19:00'
        },
        {
          course: '20:00'
        },
        {
          course: '21:00'
        },
        {
          course: '22:00'
        },
        {
          course: '23:00'
        },
        {
          course: '24:00'
        }
      ],
      classList: [],
      nowDay: '', // 今天
      nowColumnIndex: null, // 今天的columnIndex
      currentFirstDateCopy: '', // 本周的第一天
      currentFirstDate: '', // 当前周的第一天(new Date格式)
      firstDay: '', // 当前周的第一天(xxxx年xx月xx日格式)
      lastDay: '', // 当前周的最后一天
      isNow: true // // 是否为本天、本周、本月
    };
  },
  watch: {
    typeTimeTable: {
      immediate: true,
      handler(val) {
        if (val === 'week') {
          this.className = this.$route.params.classId ? this.$route.query.name : '';
          this.classId = this.$route.params.classId || '';
          this.getWeekList(new Date());
          // 本周的第一天
          const now = new Date();
          this.nowDay = this.formatDate(now);
          const week = now.getDay() - 1;
          this.currentFirstDateCopy = this.changeDate(now, week * -1);
        }
      }
    },
    searchForm: {
      immediate: true,
      deep: true,
      handler(val) {
        this.getWeekList(this.changeDate(this.currentFirstDate, 0));
      }
    },
    // 监测当前周是否为本周
    currentFirstDate: {
      immediate: true,
      handler(val) {
        const current = this.formatDate(val);
        const now = this.formatDate(this.currentFirstDateCopy);
        this.isNow = current === now;
      }
    }
  },
  created() {
    // 是否是预约页面
    if (this.$route.path.indexOf('/selectAppointmentClass') > 0) {
      this.isOrderPage = true;
    }
    this.classList = JSON.parse(JSON.stringify(this.initClassList));
  },
  methods: {
    // 当前页面为课表时
    getData(id) {
      var that = this;
      that.loading = true;
      if (this.$route.path.indexOf('/trialclass') > 0) {
        var now = new Date();
        var year = now.getFullYear();
        var month = now.getMonth() + 1;
        var day = now.getDate();
        console.log(year, month, day);
        that.form.StartTime = year + '-' + month + '-' + day;
      } else {
        that.form.StartTime = that.formatParam(that.firstDay);
      }

      that.form.EndTime = that.formatParam(that.lastDay);
      that.form.CourseName = that.searchForm.CourseName;
      that.form.TeachingModeCode = that.searchForm.TeachingModeCode;
      that.form.CoachName = that.searchForm.CoachName;
      that.form.IsFinished = null;
      that.form.IncludeClass = true;
      that.form.IncludeCourse = true;
      that.form.IncludeCoach = true;
      that.form.IncludeClassroom = true;
      that.form.IncludeMessageTemplate = true;
      that.form.IncludeDeleted = true;
      that.form.ClassId = id || null;
      that.form.SkipCount = null;
      that.form.MaxResultCount = null;
      const time = that.form.StartTime + '~' + that.form.EndTime;
      that.$emit('getTime', time);
      api_GET_ClubCourseSchedule(that.form).then(res => {
        that.handlerData(res.items);
        that.loading = false;
      }).catch(error => {
        that.loading = false;
        that.$message({ type: 'error', message: error.error.message });
      });
    },
    // 当前页面为预约时
    getOrderData() {
      var that = this;
      that.loading = true;
      const form = {
        CourseName: that.searchForm.CourseName,
        TeachingModeCode: that.searchForm.TeachingModeCode,
        StudentId: that.$route.query.studentId,
        StartTime: that.formatParam(that.firstDay),
        EndTime: that.formatParam(that.lastDay)
      };
      api_GET_ClubCourseScheduleCanBeReservedCourseSchedules(form).then(res => {
        that.handlerData(res);
        that.loading = false;
      }).catch(error => {
        that.loading = false;
        that.$message({ type: 'error', message: error.error.message });
      });
    },
    handlerData(array) {
      this.classList = JSON.parse(JSON.stringify(this.initClassList));
      for (let i = 0; i < array.length; i++) {
        const item = array[i];
        // let startHour = item.startHour < 10 ? '0' + item.startHour : item.startHour;
        const startHour = item.startHour + ':00';
        const key = this.classList.findIndex(ctem => ctem.course === startHour);
        let day = FormatDate(item.courseDate, 'dd');
        day = day < 10 ? day.substr(1, 1) : day;
        if (key !== -1) {
          if (this.classList[key][day]) {
            this.classList[key][day].push(item);
          } else {
            this.$set(this.classList[key], day, []);
            this.classList[key][day].push(item);
          }
        }
      }
    },
    // 改变课表类型
    changeType(code) {
      this.$emit('changeType', code);
    },
    // 获取当前周日期
    getWeekList(date) {
      this.dateList = [];
      this.propList = [];
      const week = date.getDay() - 1;
      date = this.changeDate(date, week * -1);
      this.currentFirstDate = new Date(date);

      for (var i = 0; i < 7; i++) {
        this.dateList.push(this.formatDate(i === 0 ? date : this.changeDate(date, 1)));
        let day = this.dateList[i];
        day = day.split('月')[1];
        day = day.substring(0, day.length - 1);
        this.propList.push(day);
      }
      this.firstDay = this.dateList[0];
      this.lastDay = this.dateList[6];

      if (this.$route.path.indexOf('/selectAppointmentClass') > 0) {
        this.isOrderPage = true;
        // 如果是预约页面，则走另一个接口
        this.getOrderData();
      } else {
        this.isOrderPage = false;
        // 获取数据
        this.getData(this.classId);
      }
    },
    changeDate(date, n) {
      date.setDate(date.getDate() + n);
      return date;
    },
    // 格式化日期
    formatDate(date) {
      const year = date.getFullYear() + '年';
      const month = (date.getMonth() + 1) + '月';
      const day = date.getDate() + '日';
      // const week = ['星期天', '星期一', '星期二', '星期三', '星期四', '星期五', '星期六'][date.getDay()];
      // return year + month + day + ' ' + week;
      return year + month + day;
    },
    // 格式化请求时的日期格式
    formatParam(date) {
      const y = date.split('年')[0];
      let str = date.split('年')[1];
      const m = str.split('月')[0];
      str = str.split('月')[1];
      const d = str.split('日')[0];
      return y + '-' + m + '-' + d;
    },
    // 上一周
    toPrev() {
      this.getWeekList(this.changeDate(this.currentFirstDate, -7));
    },
    // 下一周
    toNext() {
      this.getWeekList(this.changeDate(this.currentFirstDate, +7));
    },
    // 去往班课表
    toClassTimetable(row) {
      if (this.$route.path.indexOf('/trialclass') > 0) {
        return;
      }
      if (!this.isOrderPage) {
        const params = {
          classId: row.classId
        };
        this.$router.push({
          name: 'ClassTimetable',
          params: params,
          query: {
            name: row.className
          }
        });
      }
    },
    // 自定义表头
    renderHeader(h, { column, $index }) {
      const array = ['MON', 'TUE', 'WED', 'THU', 'FRI', 'SAT', 'SUN'];
      const date = this.dateList[$index - 1];
      if (this.nowDay === date) {
        this.nowColumnIndex = $index;
      }
      return h('div', [
        h('p', {
          class: ''
        }, array[$index - 1]),
        h('p', {
          class: ''
        }, this.propList[$index - 1])
      ]);
    },
    // 删除
    remove(data) {
      var that = this;
      that.$confirm(`您确定要删除吗？`, '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(() => {
        api_DELETE_ClubCourseScheduleId(data.id).then(res => {
          that.getData(that.classId);
          that.$message({ type: 'success', message: '删除成功!' });
        }).catch(error => {
          that.$message({ type: 'error', message: '删除失败 ' + error.error.message });
        });
      }).catch(() => {});
    },
    refresh() {
      this.getData(this.classId);
    },
    // 编辑
    edit(data) {
      this.$refs.createDialog.open('编辑', data);
    },
    // 表头单元格ClassName
    headerCellClassName({ row, column, rowIndex, columnIndex }) {
      if (columnIndex === this.nowColumnIndex && this.isNow) {
        return 'now_class';
      } else {
        return '';
      }
    },
    // 单元格ClassName
    tableCellClassName({ row, column, rowIndex, columnIndex }) {
      if (columnIndex === this.nowColumnIndex && this.isNow) {
        return 'now_class';
      } else {
        return '';
      }
    },
    formatClass(str) {
      if (str.length > 5) {
        return str.substr(0, 5) + '\n' + '...';
      }
      return str;
    }
  }
};
</script>

<style lang="scss">
.timetable_week {
  /*定义滚动条高宽及背景 高宽分别对应横竖滚动条的尺寸*/
  ::-webkit-scrollbar{
    width: 6px;
    height: 6px;
  }
  /*定义滚动条轨道 内阴影+圆角*/
  ::-webkit-scrollbar-track {
    background-color: transparent;
  }
  /*定义滑块 内阴影+圆角*/
  ::-webkit-scrollbar-thumb{
    border-radius: 12px;
    box-shadow: inset 0 0 6px rgba(0, 0, 0, .1);
    -webkit-box-shadow: inset 0 0 6px rgba(0, 0, 0, .1);
    background-color: rgba(144, 147, 153, 0.3);
  }
  .el-table {
    border: none;
    border-right: none !important;
  }
  .el-table th {
    background: #fff;
    height: 64px;
  }
  .el-table th:first-child {
    border-right: none;
    border-bottom: none;
  }
  .el-table th:nth-last-child(2) {
    border-right: none;
  }
  .el-table th:nth-child(2),th:nth-last-child(2) {
    background: #fafafa;
  }
  // 表头周几的样式
  .el-table th p:first-child{
    font-size: 12px;
    line-height: 12px;
    font-weight: 500;
    color: #71717a;
  }
  // 表头日期的样式
  .el-table th p:last-child{
    font-size: 22px;
    line-height: 32px;
    font-weight: 600;
    color: #000;
  }
  // 第二列，最后一列背景色
  .el-table tr td:nth-child(2),td:nth-last-child(1) {
    background: #fafafa;
  }
  .el-table tr td {
    height: 88px;
    padding: 0 0;
  }
  .el-table tr td:not(:first-child) .cell{
    height: 88px;
    padding: 0;
    height: 100%;
  }
  .el-table tr td:first-child {
    border: none;
    font-size: 12px;
    text-align: right;
    color: #71717a;
    line-height: 16px;
    position: relative;
    top: -16px;
  }
  // 设置今天的背景色
  .now_class {
    background-color: #eff6ff !important;
  }
  // 取消第一列的hover背景色
  .el-table tbody tr:hover>td:first-child {
    background-color: transparent !important
  }
}
</style>

<style scoped>
.current {
  width: 60px;
  height: 28px;
  background: #f4f4f5;
  line-height: 28px;
  text-align: center;
  color: #18181b;
  border-radius: 6px;
}
.left_right_btn {
  width: 28px;
  height: 28px;
  color: #18181b;
}
.date {
  width: 100%;
  height: 28px;
  line-height: 28px;
  text-align: center;
  color: #333333;
  font-size: 18px;
  font-weight: 500;
  cursor: pointer;
  vertical-align: middle;
}
.type {
  width: 46px;
  height: 28px;
  border-radius: 8px;
  cursor: pointer;
  padding: 4px 16px;
  color: #71717a;
  line-height: 20px;
}
.type_active {
  background: #1990ff;
  color: #ffffff;
}
.class_td {
  height: 96px;
  padding: 4px;
  color: #ffffff;
  vertical-align: top;
  line-height: 14px;
  box-sizing: border-box;
  border-radius: 4px;
  border: 1px solid #ffffff;
  overflow: hidden;
}
.ellipsis {
  height: 84px;
  display: -webkit-box;
  -webkit-box-orient: vertical;
  -webkit-line-clamp: 6;
  overflow: hidden;
  text-overflow: ellipsis;
  white-space: normal;
  word-break: break-all;
}
.class_name {
  height: 28px;
  line-height: 28px;
  color: #1990ff;
  font-size: 16px;
  font-weight: 600;
  vertical-align: middle;
}
</style>
